<template>
  <div class="confrontation-container">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <h2>攻防对抗模式</h2>
          <div class="status-indicator">
            <el-tag v-if="gameStatus === 'idle'" type="info">未开始</el-tag>
            <el-tag v-else-if="gameStatus === 'preparing'" type="warning">准备中</el-tag>
            <el-tag v-else-if="gameStatus === 'running'" type="success">进行中</el-tag>
            <el-tag v-else-if="gameStatus === 'paused'" type="warning">已暂停</el-tag>
            <el-tag v-else-if="gameStatus === 'completed'" type="success">已结束</el-tag>
          </div>
        </div>
      </template>
      <div class="mode-description">
        <p>攻防对抗模式模拟真实的工控系统攻防对抗场景，红蓝对抗通过实战演练提升工控系统安全防护能力和攻击检测能力。</p>
      </div>
    </el-card>

    <div class="main-content">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-card class="battlefield-card">
            <template #header>
              <div class="card-header">
                <h3>对抗场景</h3>
              </div>
            </template>
            <div class="battlefield-list">
              <el-radio-group v-model="selectedBattlefield" @change="handleBattlefieldChange">
                <el-radio-button v-for="item in battlefieldList" :key="item.id" :label="item.id">
                  {{ item.name }}
                </el-radio-button>
              </el-radio-group>
              
              <div v-if="currentBattlefield" class="battlefield-details">
                <div class="battlefield-info">
                  <h4>{{ currentBattlefield.name }}</h4>
                  <p>{{ currentBattlefield.description }}</p>
                </div>
                
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="场景类型">{{ currentBattlefield.type }}</el-descriptions-item>
                  <el-descriptions-item label="难度级别">
                    <el-rate
                      v-model="currentBattlefield.difficulty"
                      disabled
                      show-score
                      text-color="#ff9900"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="设备类型">{{ currentBattlefield.deviceTypes }}</el-descriptions-item>
                  <el-descriptions-item label="对抗方">攻击方(红队) vs 防守方(蓝队)</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="16">
          <el-card v-if="currentBattlefield" class="game-card">
            <template #header>
              <div class="card-header">
                <h3>对抗配置</h3>
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    @click="startGame" 
                    :disabled="gameStatus === 'running' || gameStatus === 'paused'"
                  >
                    开始对抗
                  </el-button>
                  <el-button 
                    v-if="gameStatus === 'running'" 
                    type="warning" 
                    @click="pauseGame"
                  >
                    暂停
                  </el-button>
                  <el-button 
                    v-if="gameStatus === 'paused'" 
                    type="success" 
                    @click="resumeGame"
                  >
                    继续
                  </el-button>
                  <el-button 
                    v-if="gameStatus !== 'idle' && gameStatus !== 'completed'" 
                    type="danger" 
                    @click="stopGame"
                  >
                    停止
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-tabs v-model="activeTab" class="game-tabs">
              <el-tab-pane label="对抗设置" name="settings">
                <div class="game-settings">
                  <el-form :model="gameForm" label-width="120px" :disabled="gameStatus !== 'idle'">
                    <el-form-item label="角色选择">
                      <el-radio-group v-model="gameForm.role">
                        <el-radio-button label="attacker">攻击方(红队)</el-radio-button>
                        <el-radio-button label="defender">防守方(蓝队)</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    
                    <el-form-item label="对手类型">
                      <el-radio-group v-model="gameForm.opponentType">
                        <el-radio-button label="ai">AI对手</el-radio-button>
                        <el-radio-button label="human" disabled>真人对手(开发中)</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    
                    <el-form-item label="对手难度" v-if="gameForm.opponentType === 'ai'">
                      <el-select v-model="gameForm.aiLevel">
                        <el-option label="初级" value="beginner" />
                        <el-option label="中级" value="intermediate" />
                        <el-option label="高级" value="advanced" />
                        <el-option label="专家" value="expert" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="对抗时长">
                      <el-select v-model="gameForm.duration">
                        <el-option label="30分钟" value="30" />
                        <el-option label="60分钟" value="60" />
                        <el-option label="90分钟" value="90" />
                        <el-option label="120分钟" value="120" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="攻击方可用技术" v-if="gameForm.role === 'attacker'">
                      <el-select
                        v-model="gameForm.attackTechniques"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in attackTechniquesOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="防守方可用工具" v-if="gameForm.role === 'defender'">
                      <el-select
                        v-model="gameForm.defenseTools"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in defenseToolsOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="对抗规则">
                      <el-checkbox-group v-model="gameForm.rules">
                        <el-checkbox label="captureFlag">夺旗模式</el-checkbox>
                        <el-checkbox label="timeLimit">时间限制</el-checkbox>
                        <el-checkbox label="systemDamage">系统损坏计分</el-checkbox>
                        <el-checkbox label="detectScore">检测计分</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-form>
                </div>
              </el-tab-pane>
              
              <el-tab-pane label="对抗状态" name="status" :disabled="gameStatus === 'idle'">
                <div class="battlefield-status">
                  <div class="teams-status">
                    <div class="team red-team">
                      <h4>红队状态</h4>
                      <div class="team-stats">
                        <div class="stat-item">
                          <span class="stat-label">攻击成功</span>
                          <span class="stat-value">{{ redTeamStats.successAttacks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">攻击失败</span>
                          <span class="stat-value">{{ redTeamStats.failedAttacks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">控制设备</span>
                          <span class="stat-value">{{ redTeamStats.controlledDevices }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">得分</span>
                          <span class="stat-value score">{{ redTeamStats.score }}</span>
                        </div>
                      </div>
                    </div>
                    
                    <div class="vs-divider">VS</div>
                    
                    <div class="team blue-team">
                      <h4>蓝队状态</h4>
                      <div class="team-stats">
                        <div class="stat-item">
                          <span class="stat-label">拦截攻击</span>
                          <span class="stat-value">{{ blueTeamStats.interceptedAttacks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">漏检攻击</span>
                          <span class="stat-value">{{ blueTeamStats.missedAttacks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">保护设备</span>
                          <span class="stat-value">{{ blueTeamStats.protectedDevices }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">得分</span>
                          <span class="stat-value score">{{ blueTeamStats.score }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div class="system-status">
                    <h4>系统状态</h4>
                    <el-table :data="systemStatusList" border style="width: 100%">
                      <el-table-column prop="name" label="系统/设备名称" />
                      <el-table-column prop="type" label="类型" width="120" />
                      <el-table-column label="状态" width="120">
                        <template #default="scope">
                          <el-tag :type="getSystemStatusType(scope.row.status)">
                            {{ getSystemStatusText(scope.row.status) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="控制方" width="120">
                        <template #default="scope">
                          <el-tag v-if="scope.row.controller === 'red'" type="danger">红队</el-tag>
                          <el-tag v-else-if="scope.row.controller === 'blue'" type="primary">蓝队</el-tag>
                          <el-tag v-else type="info">中立</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column prop="securityLevel" label="安全等级" width="120">
                        <template #default="scope">
                          <el-progress 
                            :percentage="scope.row.securityLevel" 
                            :color="getSecurityLevelColor(scope.row.securityLevel)"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </el-tab-pane>
              
              <el-tab-pane label="事件日志" name="events" :disabled="gameStatus === 'idle'">
                <div class="event-log">
                  <div class="event-filter">
                    <el-radio-group v-model="eventFilter" size="small">
                      <el-radio-button label="all">全部事件</el-radio-button>
                      <el-radio-button label="attack">攻击事件</el-radio-button>
                      <el-radio-button label="defense">防御事件</el-radio-button>
                      <el-radio-button label="system">系统事件</el-radio-button>
                    </el-radio-group>
                  </div>
                  
                  <div class="event-list">
                    <el-timeline>
                      <el-timeline-item
                        v-for="(event, index) in filteredEvents"
                        :key="index"
                        :type="getEventType(event)"
                        :color="getEventColor(event)"
                        :timestamp="event.time"
                        :hollow="event.important"
                      >
                        <div class="event-content">
                          <div class="event-title">
                            <span>{{ event.title }}</span>
                            <el-tag 
                              v-if="event.team" 
                              size="small"
                              :type="event.team === 'red' ? 'danger' : 'primary'"
                            >
                              {{ event.team === 'red' ? '红队' : '蓝队' }}
                            </el-tag>
                          </div>
                          <p class="event-description">{{ event.description }}</p>
                          <div v-if="event.result" class="event-result">
                            <el-tag 
                              size="small"
                              :type="event.result === 'success' ? 'success' : 'danger'"
                            >
                              {{ event.result === 'success' ? '成功' : '失败' }}
                            </el-tag>
                          </div>
                        </div>
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
            
            <div v-if="gameStatus === 'running' || gameStatus === 'paused'" class="game-progress">
              <h4>对抗进度</h4>
              <el-progress 
                :percentage="gameProgress" 
                :status="gameStatus === 'paused' ? 'warning' : ''"
              />
              <div class="time-remaining">
                <span>剩余时间: {{ formatTime(timeRemaining) }}</span>
              </div>
            </div>
            
            <div v-if="gameStatus === 'completed'" class="game-result">
              <el-result
                :icon="gameWinner === 'red' ? 'error' : 'success'"
                :title="getWinnerTitle()"
                :sub-title="getWinnerSubtitle()"
              >
                <template #extra>
                  <el-button type="primary" @click="viewGameReport">查看详细报告</el-button>
                  <el-button @click="resetGame">重新开始</el-button>
                </template>
              </el-result>
              
              <el-card class="score-card">
                <template #header>
                  <div class="card-header">
                    <h3>最终得分</h3>
                  </div>
                </template>
                <div class="final-score">
                  <div class="team-score red-team">
                    <h4>红队得分</h4>
                    <div class="score-value">{{ redTeamStats.score }}</div>
                  </div>
                  
                  <div class="score-divider">:</div>
                  
                  <div class="team-score blue-team">
                    <h4>蓝队得分</h4>
                    <div class="score-value">{{ blueTeamStats.score }}</div>
                  </div>
                </div>
              </el-card>
            </div>
          </el-card>
          
          <el-empty
            v-else
            description="请选择一个对抗场景"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';

// 游戏状态
const gameStatus = ref('idle'); // idle, preparing, running, paused, completed
const gameProgress = ref(0);
const gameTimer = ref(null);
const selectedBattlefield = ref(null);
const activeTab = ref('settings');
const eventFilter = ref('all');
const timeRemaining = ref(0);
const gameWinner = ref(null);

// 对抗场景列表
const battlefieldList = reactive([
  {
    id: 1,
    name: '工厂自动化系统',
    type: '离散制造工控系统',
    description: '典型离散制造工厂自动化控制系统环境，包含多条生产线、多种控制设备和网络',
    difficulty: 3,
    deviceTypes: 'PLC控制器、HMI工作站、SCADA系统、工业网关',
    systems: [
      { name: '中央SCADA系统', type: '监控系统', status: 'normal', controller: 'neutral', securityLevel: 80 },
      { name: '1号生产线PLC', type: '控制器', status: 'normal', controller: 'neutral', securityLevel: 70 },
      { name: '2号生产线PLC', type: '控制器', status: 'normal', controller: 'neutral', securityLevel: 70 },
      { name: '工程师站', type: '工作站', status: 'normal', controller: 'neutral', securityLevel: 60 },
      { name: '工业网关', type: '网络设备', status: 'normal', controller: 'neutral', securityLevel: 75 },
      { name: '历史数据服务器', type: '数据系统', status: 'normal', controller: 'neutral', securityLevel: 65 }
    ]
  },
  {
    id: 2,
    name: '变电站自动化系统',
    type: '电力工控系统',
    description: '智能变电站自动化系统环境，包含多个智能电气设备、保护装置和通信网络',
    difficulty: 4,
    deviceTypes: 'IED智能电子设备、RTU、通信网关、站控系统',
    systems: [
      { name: '站控计算机', type: '监控系统', status: 'normal', controller: 'neutral', securityLevel: 85 },
      { name: '保护装置A', type: '保护设备', status: 'normal', controller: 'neutral', securityLevel: 90 },
      { name: '保护装置B', type: '保护设备', status: 'normal', controller: 'neutral', securityLevel: 90 },
      { name: '智能终端IED-1', type: '控制器', status: 'normal', controller: 'neutral', securityLevel: 75 },
      { name: '智能终端IED-2', type: '控制器', status: 'normal', controller: 'neutral', securityLevel: 75 },
      { name: '通信网关', type: '网络设备', status: 'normal', controller: 'neutral', securityLevel: 80 },
      { name: '远程终端RTU', type: '控制器', status: 'normal', controller: 'neutral', securityLevel: 70 }
    ]
  },
  {
    id: 3,
    name: '石化过程控制系统',
    type: '过程控制工控系统',
    description: '石化企业过程控制系统环境，包含DCS控制系统、安全仪表系统、先进控制系统等',
    difficulty: 5,
    deviceTypes: 'DCS控制站、操作员站、安全仪表系统、先进控制计算机',
    systems: [
      { name: '中央DCS系统', type: '控制系统', status: 'normal', controller: 'neutral', securityLevel: 85 },
      { name: '操作员站A', type: '工作站', status: 'normal', controller: 'neutral', securityLevel: 75 },
      { name: '操作员站B', type: '工作站', status: 'normal', controller: 'neutral', securityLevel: 75 },
      { name: '工程师站', type: '工作站', status: 'normal', controller: 'neutral', securityLevel: 70 },
      { name: '安全仪表系统', type: '安全系统', status: 'normal', controller: 'neutral', securityLevel: 95 },
      { name: '先进控制计算机', type: '控制系统', status: 'normal', controller: 'neutral', securityLevel: 80 },
      { name: '生产管理系统', type: '管理系统', status: 'normal', controller: 'neutral', securityLevel: 65 },
      { name: '边界防火墙', type: '安全设备', status: 'normal', controller: 'neutral', securityLevel: 90 }
    ]
  }
]);

// 当前场景
const currentBattlefield = computed(() => {
  if (!selectedBattlefield.value) return null;
  return battlefieldList.find(item => item.id === selectedBattlefield.value) || null;
});

// 当前系统状态列表
const systemStatusList = ref([]);

// 游戏配置表单
const gameForm = reactive({
  role: 'attacker',  // attacker, defender
  opponentType: 'ai',  // ai, human
  aiLevel: 'intermediate',  // beginner, intermediate, advanced, expert
  duration: '60',
  attackTechniques: [1, 2, 6],
  defenseTools: [1, 3, 5],
  rules: ['captureFlag', 'timeLimit', 'systemDamage']
});

// 攻击方法选项
const attackTechniquesOptions = ref([
  { id: 1, name: '网络扫描技术', category: '渗透', type: '外部' },
  { id: 2, name: '漏洞利用技术', category: '渗透', type: '外部' },
  { id: 3, name: 'SSH服务爆破', category: '渗透', type: '外部' },
  { id: 4, name: '跨站脚本攻击', category: '渗透', type: '外部' },
  { id: 5, name: 'SQL注入攻击', category: '渗透', type: '外部' },
  { id: 6, name: '工控协议漏洞利用', category: '渗透', type: '外部' },
  { id: 7, name: 'Modbus协议攻击', category: '植入', type: '内部' },
  { id: 8, name: 'DNP3协议攻击', category: '植入', type: '内部' },
  { id: 9, name: 'PLC固件修改', category: '植入', type: '内部' },
  { id: 10, name: 'SCADA系统后门植入', category: '植入', type: '内部' }
]);

// 防御工具选项
const defenseToolsOptions = ref([
  { id: 1, name: '网络入侵检测系统', category: '监测', type: '网络' },
  { id: 2, name: '主机入侵检测系统', category: '监测', type: '主机' },
  { id: 3, name: '异常行为检测系统', category: '监测', type: '行为' },
  { id: 4, name: '网络流量分析工具', category: '分析', type: '网络' },
  { id: 5, name: '工控协议深度检测', category: '监测', type: '协议' },
  { id: 6, name: '工控防火墙', category: '防护', type: '网络' },
  { id: 7, name: '白名单控制系统', category: '防护', type: '应用' },
  { id: 8, name: '安全日志分析系统', category: '分析', type: '日志' },
  { id: 9, name: '安全态势感知平台', category: '分析', type: '综合' },
  { id: 10, name: '应急响应自动化工具', category: '响应', type: '自动化' }
]);

// 红队统计数据
const redTeamStats = reactive({
  successAttacks: 0,
  failedAttacks: 0,
  controlledDevices: 0,
  score: 0
});

// 蓝队统计数据
const blueTeamStats = reactive({
  interceptedAttacks: 0,
  missedAttacks: 0,
  protectedDevices: 0,
  score: 0
});

// 事件日志
const eventLogs = ref([]);

// 过滤后的事件日志
const filteredEvents = computed(() => {
  if (eventFilter.value === 'all') {
    return eventLogs.value;
  }
  return eventLogs.value.filter(event => event.category === eventFilter.value);
});

// 获取事件类型
const getEventType = (event) => {
  return event.type || 'primary';
};

// 获取事件颜色
const getEventColor = (event) => {
  const typeMap = {
    'primary': '#409EFF',
    'success': '#67C23A',
    'warning': '#E6A23C',
    'danger': '#F56C6B',
    'info': '#909399'
  };
  return typeMap[event.type] || '#409EFF';
};

// 获取系统状态类型
const getSystemStatusType = (status) => {
  const statusMap = {
    'normal': 'success',
    'warning': 'warning',
    'danger': 'danger',
    'offline': 'info',
    'compromised': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取系统状态文本
const getSystemStatusText = (status) => {
  const statusMap = {
    'normal': '正常',
    'warning': '警告',
    'danger': '危险',
    'offline': '离线',
    'compromised': '已被入侵'
  };
  return statusMap[status] || '未知';
};

// 获取安全等级颜色
const getSecurityLevelColor = (level) => {
  if (level < 40) return '#F56C6B';
  if (level < 70) return '#E6A23C';
  return '#67C23A';
};

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 获取胜利者标题
const getWinnerTitle = () => {
  if (gameWinner.value === 'red') {
    return '红队胜利';
  } else if (gameWinner.value === 'blue') {
    return '蓝队胜利';
  } else {
    return '平局';
  }
};

// 获取胜利者副标题
const getWinnerSubtitle = () => {
  if (gameWinner.value === 'red') {
    return '攻击方成功破坏了防御系统';
  } else if (gameWinner.value === 'blue') {
    return '防守方成功保护了系统安全';
  } else {
    return '双方实力相当，难分胜负';
  }
};

// 处理场景变更
const handleBattlefieldChange = (battlefieldId) => {
  if (gameStatus.value !== 'idle' && gameStatus.value !== 'completed') {
    ElMessageBox.confirm(
      '切换场景将终止当前对抗进度，确定要继续吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      stopGame();
      selectedBattlefield.value = battlefieldId;
      initSystemStatus();
    }).catch(() => {
      selectedBattlefield.value = selectedBattlefield.value;
    });
  } else {
    initSystemStatus();
  }
};

// 初始化系统状态
const initSystemStatus = () => {
  if (currentBattlefield.value && currentBattlefield.value.systems) {
    systemStatusList.value = JSON.parse(JSON.stringify(currentBattlefield.value.systems));
  }
};

// 开始对抗
const startGame = () => {
  if (!currentBattlefield.value) {
    ElMessage.warning('请先选择一个对抗场景');
    return;
  }
  
  gameStatus.value = 'preparing';
  resetStats();
  initSystemStatus();
  eventLogs.value = [];
  
  // 添加游戏开始事件
  addEventLog({
    title: '对抗开始',
    description: `在${currentBattlefield.value.name}场景中开始攻防对抗`,
    time: getCurrentTime(),
    type: 'primary',
    category: 'system',
    important: true
  });
  
  // 设置计时器
  timeRemaining.value = parseInt(gameForm.duration) * 60;
  
  // 模拟准备过程
  setTimeout(() => {
    gameStatus.value = 'running';
    gameProgress.value = 0;
    activeTab.value = 'status';
    
    // 模拟对抗进度
    gameTimer.value = setInterval(() => {
      gameProgress.value = Math.min(100, gameProgress.value + (100 / (timeRemaining.value / 3)));
      timeRemaining.value--;
      
      // 随机生成事件
      if (Math.random() < 0.1) {
        generateRandomEvent();
      }
      
      // 对抗结束逻辑
      if (timeRemaining.value <= 0 || gameProgress.value >= 100) {
        endGame();
      }
    }, 1000);
  }, 1500);
};

// 添加事件日志
const addEventLog = (event) => {
  eventLogs.value = [event, ...eventLogs.value];
  if (eventLogs.value.length > 50) {
    eventLogs.value = eventLogs.value.slice(0, 50);
  }
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
};

// 重置统计数据
const resetStats = () => {
  // 重置红队数据
  redTeamStats.successAttacks = 0;
  redTeamStats.failedAttacks = 0;
  redTeamStats.controlledDevices = 0;
  redTeamStats.score = 0;
  
  // 重置蓝队数据
  blueTeamStats.interceptedAttacks = 0;
  blueTeamStats.missedAttacks = 0;
  blueTeamStats.protectedDevices = 0;
  blueTeamStats.score = 0;
};

// 随机生成事件
const generateRandomEvent = () => {
  // 根据角色生成相应的事件
  if (gameForm.role === 'attacker') {
    generateAttackEvent();
  } else {
    generateDefenseEvent();
  }
};

// 生成攻击事件
const generateAttackEvent = () => {
  // 随机选择一个系统
  const systemIndex = Math.floor(Math.random() * systemStatusList.value.length);
  const targetSystem = systemStatusList.value[systemIndex];
  
  // 随机选择一个攻击方法
  const attackIndex = Math.floor(Math.random() * gameForm.attackTechniques.length);
  const attackId = gameForm.attackTechniques[attackIndex];
  const attackTechnique = attackTechniquesOptions.value.find(t => t.id === attackId);
  
  // 随机决定攻击是否成功
  const isSuccess = Math.random() < 0.6; // 60%成功率
  
  if (isSuccess) {
    // 攻击成功
    redTeamStats.successAttacks++;
    redTeamStats.score += 10;
    blueTeamStats.missedAttacks++;
    
    // 修改系统状态
    targetSystem.status = 'compromised';
    targetSystem.controller = 'red';
    targetSystem.securityLevel = Math.max(0, targetSystem.securityLevel - 30);
    redTeamStats.controlledDevices = systemStatusList.value.filter(s => s.controller === 'red').length;
    
    // 添加事件日志
    addEventLog({
      title: `使用${attackTechnique.name}攻击${targetSystem.name}`,
      description: `成功利用${attackTechnique.name}获取了对${targetSystem.name}的控制权`,
      time: getCurrentTime(),
      type: 'danger',
      category: 'attack',
      team: 'red',
      result: 'success',
      important: true
    });
    
    // AI防守方反应
    setTimeout(() => {
      if (Math.random() < 0.4) { // 40%的概率反制
        blueTeamStats.interceptedAttacks++;
        blueTeamStats.score += 5;
        
        targetSystem.status = 'warning';
        targetSystem.controller = 'blue';
        targetSystem.securityLevel = Math.min(100, targetSystem.securityLevel + 20);
        blueTeamStats.protectedDevices = systemStatusList.value.filter(s => s.controller === 'blue').length;
        
        addEventLog({
          title: `蓝队发现攻击并反制`,
          description: `蓝队成功发现并清除了${targetSystem.name}上的入侵`,
          time: getCurrentTime(),
          type: 'primary',
          category: 'defense',
          team: 'blue',
          result: 'success'
        });
      }
    }, 5000);
    
  } else {
    // 攻击失败
    redTeamStats.failedAttacks++;
    blueTeamStats.interceptedAttacks++;
    blueTeamStats.score += 5;
    
    // 添加事件日志
    addEventLog({
      title: `使用${attackTechnique.name}攻击${targetSystem.name}`,
      description: `攻击被防御系统拦截，未能成功入侵${targetSystem.name}`,
      time: getCurrentTime(),
      type: 'warning',
      category: 'attack',
      team: 'red',
      result: 'failed'
    });
  }
};

// 生成防御事件
const generateDefenseEvent = () => {
  // 随机选择一个系统
  const systemIndex = Math.floor(Math.random() * systemStatusList.value.length);
  const targetSystem = systemStatusList.value[systemIndex];
  
  // 随机选择一个防御工具
  const defenseIndex = Math.floor(Math.random() * gameForm.defenseTools.length);
  const defenseId = gameForm.defenseTools[defenseIndex];
  const defenseTool = defenseToolsOptions.value.find(t => t.id === defenseId);
  
  // 随机决定是否有攻击发生
  const isAttackHappening = Math.random() < 0.7; // 70%概率有攻击
  
  if (isAttackHappening) {
    // 随机选择一个攻击方法
    const attackIndex = Math.floor(Math.random() * attackTechniquesOptions.value.length);
    const attackTechnique = attackTechniquesOptions.value[attackIndex];
    
    // 随机决定防御是否成功
    const isSuccess = Math.random() < 0.7; // 70%成功率
    
    if (isSuccess) {
      // 防御成功
      blueTeamStats.interceptedAttacks++;
      blueTeamStats.score += 10;
      redTeamStats.failedAttacks++;
      
      // 修改系统状态
      targetSystem.status = 'warning';
      targetSystem.controller = 'blue';
      targetSystem.securityLevel = Math.min(100, targetSystem.securityLevel + 10);
      blueTeamStats.protectedDevices = systemStatusList.value.filter(s => s.controller === 'blue').length;
      
      // 添加事件日志
      addEventLog({
        title: `使用${defenseTool.name}拦截攻击`,
        description: `成功拦截了对${targetSystem.name}的${attackTechnique.name}攻击`,
        time: getCurrentTime(),
        type: 'success',
        category: 'defense',
        team: 'blue',
        result: 'success'
      });
      
    } else {
      // 防御失败
      blueTeamStats.missedAttacks++;
      redTeamStats.successAttacks++;
      redTeamStats.score += 15;
      
      // 修改系统状态
      targetSystem.status = 'compromised';
      targetSystem.controller = 'red';
      targetSystem.securityLevel = Math.max(0, targetSystem.securityLevel - 30);
      redTeamStats.controlledDevices = systemStatusList.value.filter(s => s.controller === 'red').length;
      
      // 添加事件日志
      addEventLog({
        title: `使用${defenseTool.name}拦截攻击失败`,
        description: `未能阻止对${targetSystem.name}的${attackTechnique.name}攻击，系统已被入侵`,
        time: getCurrentTime(),
        type: 'danger',
        category: 'defense',
        team: 'blue',
        result: 'failed',
        important: true
      });
      
      // 尝试恢复
      setTimeout(() => {
        if (Math.random() < 0.5) { // 50%的概率恢复
          targetSystem.status = 'warning';
          targetSystem.controller = 'blue';
          targetSystem.securityLevel = Math.min(100, targetSystem.securityLevel + 20);
          blueTeamStats.protectedDevices = systemStatusList.value.filter(s => s.controller === 'blue').length;
          blueTeamStats.score += 5;
          
          addEventLog({
            title: `系统恢复`,
            description: `成功恢复了${targetSystem.name}的安全状态`,
            time: getCurrentTime(),
            type: 'success',
            category: 'defense',
            team: 'blue',
            result: 'success'
          });
        }
      }, 8000);
    }
  } else {
    // 没有攻击发生，只是巡检
    targetSystem.securityLevel = Math.min(100, targetSystem.securityLevel + 5);
    
    // 添加事件日志
    addEventLog({
      title: `系统巡检`,
      description: `使用${defenseTool.name}对${targetSystem.name}进行安全巡检`,
      time: getCurrentTime(),
      type: 'info',
      category: 'defense',
      team: 'blue'
    });
  }
};

// 结束对抗
const endGame = () => {
  clearInterval(gameTimer.value);
  gameStatus.value = 'completed';
  gameProgress.value = 100;
  timeRemaining.value = 0;
  
  // 决定胜利方
  if (redTeamStats.score > blueTeamStats.score) {
    gameWinner.value = 'red';
  } else if (blueTeamStats.score > redTeamStats.score) {
    gameWinner.value = 'blue';
  } else {
    gameWinner.value = 'draw';
  }
  
  // 添加游戏结束事件
  addEventLog({
    title: '对抗结束',
    description: `${getWinnerTitle()}，最终比分 红队${redTeamStats.score}:${blueTeamStats.score}蓝队`,
    time: getCurrentTime(),
    type: 'primary',
    category: 'system',
    important: true
  });
  
  ElMessage.success('对抗已结束');
};

// 暂停对抗
const pauseGame = () => {
  if (gameStatus.value === 'running') {
    gameStatus.value = 'paused';
    clearInterval(gameTimer.value);
    ElMessage.info('对抗已暂停');
  }
};

// 继续对抗
const resumeGame = () => {
  if (gameStatus.value === 'paused') {
    gameStatus.value = 'running';
    
    // 继续计时器
    gameTimer.value = setInterval(() => {
      gameProgress.value = Math.min(100, gameProgress.value + (100 / (timeRemaining.value / 3)));
      timeRemaining.value--;
      
      // 随机生成事件
      if (Math.random() < 0.1) {
        generateRandomEvent();
      }
      
      // 对抗结束逻辑
      if (timeRemaining.value <= 0 || gameProgress.value >= 100) {
        endGame();
      }
    }, 1000);
    
    ElMessage.info('对抗已继续');
  }
};

// 停止对抗
const stopGame = () => {
  if (gameStatus.value !== 'idle' && gameStatus.value !== 'completed') {
    clearInterval(gameTimer.value);
    gameStatus.value = 'idle';
    gameProgress.value = 0;
    timeRemaining.value = 0;
    
    // 重置系统状态
    initSystemStatus();
    
    // 添加事件日志
    addEventLog({
      title: '对抗中止',
      description: '对抗被手动中止',
      time: getCurrentTime(),
      type: 'warning',
      category: 'system'
    });
    
    ElMessage.warning('对抗已停止');
  }
};

// 重置对抗
const resetGame = () => {
  gameStatus.value = 'idle';
  gameProgress.value = 0;
  timeRemaining.value = 0;
  clearInterval(gameTimer.value);
  resetStats();
  initSystemStatus();
  eventLogs.value = [];
  activeTab.value = 'settings';
};

// 查看对抗报告
const viewGameReport = () => {
  ElMessageBox.alert(
    '详细对抗报告功能正在开发中，敬请期待',
    '功能提示',
    {
      confirmButtonText: '确定'
    }
  );
};

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  if (gameTimer.value) {
    clearInterval(gameTimer.value);
  }
});
</script>

<style lang="scss" scoped>
.confrontation-container {
  padding: 16px;
  
  .header-card {
    margin-bottom: 16px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h2 {
        margin: 0;
        font-size: 18px;
        color: var(--text-color);
      }
    }
    
    .mode-description {
      margin-top: 10px;
      color: var(--text-color-secondary);
    }
  }
  
  .main-content {
    margin-bottom: 16px;
    
    .battlefield-card {
      height: 100%;
      
      .card-header {
        h3 {
          margin: 0;
          font-size: 16px;
          color: var(--text-color);
        }
      }
      
      .battlefield-list {
        display: flex;
        flex-direction: column;
        gap: 16px;
        
        .battlefield-details {
          margin-top: 16px;
          
          .battlefield-info {
            margin-bottom: 16px;
            
            h4 {
              margin: 0 0 8px;
              font-size: 16px;
              color: var(--text-color);
            }
            
            p {
              color: var(--text-color-secondary);
              margin: 0;
            }
          }
        }
      }
    }
    
    .game-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 16px;
          color: var(--text-color);
        }
        
        .action-buttons {
          display: flex;
          gap: 8px;
        }
      }
      
      .game-tabs {
        margin-bottom: 16px;
        
        .game-settings {
          padding: 8px 0;
        }
        
        .battlefield-status {
          .teams-status {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            
            .team {
              flex: 1;
              padding: 16px;
              border-radius: 4px;
              
              h4 {
                margin: 0 0 16px;
                font-size: 16px;
                color: var(--text-color);
                text-align: center;
              }
              
              &.red-team {
                background-color: rgba(245, 108, 108, 0.1);
                
                .score {
                  color: #F56C6B;
                }
              }
              
              &.blue-team {
                background-color: rgba(64, 158, 255, 0.1);
                
                .score {
                  color: #409EFF;
                }
              }
              
              .team-stats {
                display: flex;
                flex-wrap: wrap;
                gap: 12px;
                
                .stat-item {
                  flex: 1 0 45%;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  
                  .stat-label {
                    font-size: 12px;
                    color: var(--text-color-secondary);
                    margin-bottom: 4px;
                  }
                  
                  .stat-value {
                    font-size: 18px;
                    font-weight: bold;
                    color: var(--text-color);
                    
                    &.score {
                      font-size: 24px;
                    }
                  }
                }
              }
            }
            
            .vs-divider {
              width: 60px;
              text-align: center;
              font-size: 20px;
              font-weight: bold;
              color: var(--text-color);
            }
          }
          
          .system-status {
            h4 {
              margin: 0 0 16px;
              font-size: 16px;
              color: var(--text-color);
            }
          }
        }
        
        .event-log {
          .event-filter {
            margin-bottom: 16px;
          }
          
          .event-list {
            .event-content {
              .event-title {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8px;
                font-weight: bold;
                color: var(--text-color);
              }
              
              .event-description {
                margin: 4px 0;
                color: var(--text-color-secondary);
              }
              
              .event-result {
                margin-top: 8px;
              }
            }
          }
        }
      }
      
      .game-progress {
        margin-top: 24px;
        
        h4 {
          margin: 0 0 8px;
          font-size: 14px;
          color: var(--text-color);
        }
        
        .time-remaining {
          margin-top: 8px;
          text-align: right;
          font-size: 14px;
          color: var(--text-color-secondary);
        }
      }
      
      .game-result {
        margin-top: 24px;
        
        .score-card {
          margin-top: 24px;
          
          .final-score {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 24px 0;
            
            .team-score {
              text-align: center;
              
              h4 {
                margin: 0 0 16px;
                font-size: 16px;
                color: var(--text-color);
              }
              
              .score-value {
                font-size: 48px;
                font-weight: bold;
              }
              
              &.red-team .score-value {
                color: #F56C6B;
              }
              
              &.blue-team .score-value {
                color: #409EFF;
              }
            }
            
            .score-divider {
              margin: 0 24px;
              font-size: 36px;
              font-weight: bold;
              color: var(--text-color-secondary);
            }
          }
        }
      }
    }
  }
}
</style> 